<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/1/15
 * Time: 23:05
 */
namespace app\api\logic;


use app\common\model\User;
use app\common\model\zbtask\Zbcategory;
use app\common\model\zbtask\Zbtask;
use app\common\utils\Utils;
use think\Db;
use think\exception\ValidateException;
use think\Model;

class Money
{

    private static $new;
    private $money;
    private $user_id;
    private $where = [
        'type' => 1,
        'status' => 1
    ];
    private function __construct() {
        $this->money = new \app\common\model\zbtask\Money();
    }


    public static function instance () { //声明一个静态公共方法，供外部获取唯一实例
        if (!(self::$new instanceof self)) {
            self::$new = new self;
        }
        return self::$new;
    }

    public function get($id) {
        $money = $this->money->get($id);
        if (!$money) {
            throw new ValidateException('未获取到众包费');
        }

        return $money;
    }
    /**
     * 设置查询用户
     * @param $user_id
     * @return  object
     */
    public function setUserId($user_id) {
        $this->user_id = $user_id;
        return $this;
    }

    /**
     * 设置查询用户
     * @param $where
     * @return  object $this
     */
    public function where($where = []) {
        //设置where条件
        $this->where = array_merge($this->where, $where);
        return $this;
    }

    public function getMoneyList($type = 1, $where = []) {
        if($type == 1) {
            //待发
            $where['transfer_type'] = ['in', [0, 1, 3]];
        } else {
            //已发
            $where['transfer_type'] = 2;
        }
        $this->where = array_merge($this->where, $where);

        $list = $this->money
            ->where($this->where)
            ->order('createtime desc')
            ->paginate()->each(function ($item, $key) {
                $item['task_info'] = Zbtask::where(['id'=> $item->task_id])->find()->visible(['id', 'name', 'zbcategory_id']);
                $item['category'] = Zbcategory::where(['id' =>  $item['task_info']['zbcategory_id']])->find()->visible(['image', 'id']);
            });

        return $list;
    }

    /**
     * 统计
     * @param array $where
     * @return array
     */
    public function moneySum($where=[]) {
        if ($this->user_id) {
            $where['user_id'] = $this->user_id;
        }
        $where['type'] = 1 ;  //审核通过
        $where['status'] = 1; //有效

        $yes = $this->money->where($where)->where('transfer_type', 'eq', 2)->sum('money') ?? 0.00;
        $no = $this->money->where($where)->where('transfer_type', 'in', [0, 1, 3])->sum('money') ?? 0.00; //为计算打款失败

        return ['no' => $no, 'yes' => $yes];
    }

    /**处理单条众包费结果*/
    public function processGet(Model $money) {
        $money['task_info'] = Zbtask::where(['id'=> $money->task_id])->find()->visible(['id', 'name', 'zbcategory_id', 'introduce']);
        $money['category'] = Zbcategory::where(['id' =>  $money['task_info']['zbcategory_id']])->find()->visible(['image', 'id']);
        $money['userInfo'] = User::field('id,real_name,identity_card')->find($this->user_id);
        $task_count = $this->splitMoney($money['money']);
        $money['task_count'] =  count($task_count);//任务数量
        $data['createtime_text'] = Utils::time_format($money['createtime'], 'Y年m月d日');

        return $money;
    }

    /**
     *   进行众包费计算 拆分
     */
    public function splitMoney($money) {
        $moneyArr = [];
        $min = config('site.money_min');
        $max = config('site.money_max');

        if ($money <= $max) {
            array_push($moneyArr, $money);
        } else {
            $count = ceil($money/$max);
            for ($i = 1; $i < $count; $i++) {
                if ($max < $money  && $money <= ($max + $min)) {
                    $v1 = ceil($money/2);
                    $v2 = $money - $v1;
                    array_push($moneyArr, $v1);
                    array_push($moneyArr, $v2);
                    break;
                } else if ($money <= $max) {
                    array_push($moneyArr, $money);
                    break;
                } else {
                    $v = rand($min, $max);
                    $money -= $v;
                    array_push($moneyArr, $v);
                }
            }
        }

        return $moneyArr;
    }

    private function __clone() {} //声明私有的克隆方法，防止对象被克隆

    public function __sleep() { //重写__sleep方法，将返回置空，防止序列化反序列化获得新的对象
        return [];
    }

}